package com.example.jdbcdemo.controller;

import com.example.jdbcdemo.mapper.GoodsMapper;
import com.example.jdbcdemo.mapper.UserMapper;
import com.example.jdbcdemo.pojo.Goods;
import com.example.jdbcdemo.service.GoodsServiceInterface;
import com.example.jdbcdemo.utils.JsonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@RestController
public class GoodsController {

    @Autowired
    GoodsServiceInterface goodsService;
    @Autowired
    UserMapper userMapper;

    @PostMapping("/goods/add")
    public JsonUtil addGoods(@RequestBody Map<String,Integer> map){
       return goodsService.addGoods(map.get("productId"),map.get("num"),map.get("storageId"));
    }

    @PostMapping("/goods/delete")
    public JsonUtil deleteGoods(@RequestBody Map<String,Integer> map){
        return goodsService.deleteGoods(map.get("id"));
    }

    @PostMapping("/goods/list")
    public JsonUtil queryList(){
        return goodsService.queryGoodsList();
    }

    @PostMapping("/goods/update")
    public JsonUtil updateGoods(HttpServletRequest request, @RequestBody Map<String,Integer> map){
        //操作员id从token获取
        //token中包含了用户名，根据用户名获取用户id
        String token= (String) request.getHeader("token");
        String spiltss[]=token.split("#");
        String userName=spiltss[0];
        //新增权限判断，只有老板和进货调货员（对应usertype为0和1）能够修改库存
        int userType=userMapper.queryUserByname(userName).getUserType();
        if (userType!=0&&userType!=1)
        {
            return new JsonUtil(1000,"权限不足",null);
        }

        return goodsService.updateGoods(map.get("id"),map.get("productId"),map.get("num"),map.get("storageId"));
    }

    @PostMapping("/goods/detail")
    public JsonUtil queryGoodsById(@RequestBody Map<String,Integer> map){
        return goodsService.queryGoodsById(map.get("id"));
    }

    @PostMapping("/goods/trans")
    public JsonUtil transGoods(HttpServletRequest request, @RequestBody Map<String,Integer> map)
    {
        //操作员id从token获取
        //token中包含了用户名，根据用户名获取用户id
        String token= (String) request.getHeader("token");
        String spiltss[]=token.split("#");
        String userName=spiltss[0];
        //新增权限判断，只有老板和进货调货员（对应usertype为0和1）能够调拨库存
        int userType=userMapper.queryUserByname(userName).getUserType();
        if (userType!=0&&userType!=1)
        {
            return new JsonUtil(1000,"权限不足",null);
        }

        return goodsService.changeGoodsInStorage(map.get("goodsId"),map.get("targetId"),map.get("num"));
    }
}
